package mq.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 *
 * @author verlet
 * @date 2019/9/11
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 声明channel
        Channel channel = RabbitMqChannelFactory.createChannel();
        // 声明一个队列
        String queueName = "test1001";
        Map<String, Object> arguments = new HashMap<>();
        // 队列TTL为60秒
        arguments.put("x-message-ttl", 60000);
        // 设置死信队列
        arguments.put("x-dead-letter-exchange", "dlx.exchange");
        channel.queueDeclare(queueName, true, false, false, arguments);
        // 创建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("-------------自定义消费者------------");
                System.out.println("consumerTag : " + consumerTag);
                System.out.println("envelope : " + envelope);
                System.out.println("properties : " + properties);
                System.out.println("body : " + new String(body));

                // nack并重回队列
//                channel.basicNack(envelope.getDeliveryTag(),false,true);
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        /**
         * 消息限制消费
         * 1. autoAck设置false
         * 2. 设置Qos -> prefetchSize 消息的容量，prefetchCount 消息个数
         */
        channel.basicQos(0, 1, false);
        // 设置channel 为自定义消费者
        channel.basicConsume(queueName, false, consumer);
        Thread.sleep(1000);
        // 关闭连接
        RabbitMqChannelFactory.close(channel);
    }
}
